<?php

namespace app\common\library;

use Exception;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Tmt\V20180321\TmtClient;
use TencentCloud\Tmt\V20180321\Models\TextTranslateBatchRequest;
use TencentCloud\Tmt\V20180321\Models\TextTranslateRequest;
use TencentCloud\Tmt\V20180321\Models\LanguageDetectRequest;
use think\exception\HttpResponseException;

class Translation
{

    private $url = 'tmt.tencentcloudapi.com';
    private $region = 'ap-beijing';
    private $SecretId = 'AKIDvnaFSivtdYxJvHjFOfwEWrF35vliAEG3';
    private $SecretKey = '6d3LP2bvV2EJGEDOCHleUc7YxHXil3Ro';

    private $client;

    public function __construct()
    {
        $cred = new Credential($this->SecretId, $this->SecretKey);
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint($this->url);
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        $this->client = new TmtClient($cred, $this->region, $clientProfile);
    }

    /**
     * @param $text
     * @param $Source
     * @param $Target
     * @return null
     */
    public function _textTranslate($text, $Source = 'zh', $Target = 'ru')
    {
        // 实例化一个请求对象,每个接口都会对应一个request对象
        $req = new TextTranslateRequest();
        $params = [
            // 'Action' => 'TextTranslate',
            // 'Version' => '2018-03-21',
            // 'Region' => $this->region,
            'SourceText' => $text,
            'Source' => $Source,
            'Target' => $Target,
            'ProjectId' => 0
        ];
        $req->fromJsonString(json_encode($params));
        // 返回的resp是一个TextTranslateBatchResponse的实例，与请求对象对应
        try {
            $resp = $this->client->TextTranslate($req);
        } catch (Exception $e) {
            echo json_encode(['code' => 0, 'data' => null, 'msg' => $e->getMessage(), 'time' => time()]);
            die;
        }
        // $resp->toJsonString()
        return $this->object_to_array($resp);
    }

    /**
     * @param $text
     * @param string $Source
     * @param string $Target
     * @return array
     * @notes
     * @author: dongdong
     * @date: 2024/12/30 13:55
     */
    public function textTranslate($text, $Source = 'zh', $Target = 'ru')
    {
        try {
            if ($Source == 'zh') {
                $Source = 'cn';
            }
            if ($Target == 'zh') {
                $Target = 'cn';
            }
            $Translation = new Itrans();
            $ret = $Translation->xfyun($text, $Source, $Target);
            if ($text && is_string($text)) {
                if (!is_numeric($text)) {
                    if ($ret['code'] == 0) {
                        $result = $ret['data']['result'];
                        $resp = [];
                        $resp['TargetText'] = $result['trans_result']['dst'];
                    } else {
                        echo json_encode(['code' => 0, 'data' => null, 'msg' => $ret['message'], 'time' => time()]);
                        die;
                    }
                }else{
                    $result = $text;
                    $resp = [];
                    $resp['TargetText'] = $result;
                }
            }
            sleep(1);
        } catch (Exception $e) {
            echo json_encode(['code' => 0, 'data' => null, 'msg' => $e->getMessage(), 'time' => time()]);
            die;
        }
        return $resp;
    }

    /**
     * 语种识别
     * @param $text
     * @return object
     */
    public function languageDetect($text)
    {
        // 实例化一个请求对象,每个接口都会对应一个request对象
        if ($text && is_string($text)) {
            if (!is_numeric($text)) {
                $req = new LanguageDetectRequest();
                $params = [
                    'Text' => $text,
                    'ProjectId' => 0
                ];
                $req->fromJsonString(json_encode($params));
                // 返回的resp是一个TextTranslateBatchResponse的实例，与请求对象对应
                try {
                    $resp = $this->client->LanguageDetect($req);
                    return $this->object_to_array($resp);
                } catch (Exception $e) {
                    echo json_encode(['code' => 0, 'data' => null, 'msg' => $e->getMessage(), 'time' => time()]);
                    die;
                }
                // $resp->toJsonString();
            }
        }
    }

    /**
     * 快速翻译
     */
    public function quickTranslate($translate = '', $type = 'text')
    {
        if ($translate == '') {
            return ['text' => $translate, 'lang' => 'zh'];
        }
        if ($type == 'text') {
            $language = $this->languageDetect($translate)['Lang'];// 语种

            if ($language == 'zh') {
                $translated = $this->textTranslate($translate, $Source = 'zh', $Target = 'ru');
            } elseif ($language == 'ru') {
                $translated = $this->textTranslate($translate, $Source = 'ru', $Target = 'zh');
            } else {
                $translated = ['TargetText' => $translate];
                $language = 'zh';
            }
            return ['text' => $translated['TargetText'], 'lang' => $language];
        } else {
            return ['text' => $translate, 'lang' => 'zh'];
        }
    }

    /**
     * @param $obj
     * @return array
     * @notes 对象转数组
     * @author: dongdong
     * @date: 2024/12/31 11:35
     */
    public function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)$this->object_to_array($v);
            }
        }
        return $obj;
    }


    /**
     * @param $name
     * @return array
     * @notes 翻译方法
     * @author: dongdong
     * @date: 2024/12/31 11:17
     */
    public function translationSelf($name)
    {
        if(!empty($name)){
            if(is_numeric($name)){
                return ['zh' => $name, 'ru' => $name];
            }else{
                $wenzi = $this->languageDetect($name);
                $language = $wenzi['Lang'];
                if ($language == 'zh') {// 中 - 俄
                    $translated = $this->textTranslate($name, $Source = 'zh', $Target = 'ru');
                    $name_ru = $translated['TargetText'];
                } else if ($language == 'ru') {// 俄 - 中
                    $translated = $this->textTranslate($name, $Source = 'ru', $Target = 'zh');
                    $name_ru = $name;
                    $name = $translated['TargetText'];
                } else {
                    // 输入其他文字时，中俄相同
                    $name_ru = $name;
                }
                return ['zh' => $name, 'ru' => $name_ru];
            }
        }else{
            return ['zh' => '', 'ru' => ''];
        }

    }
}